//
//  ReservedWheelViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/18.
//

import UIKit

//typealias BlockCarOrderSucceed = () ->Void

class ReservedWheelViewController: BaseViewController {
    var tableView: BaseTableView!
    var protocolBtn: UIButton!
    var haveRead = false//是否阅读了协议
    var overView: WBPopOverView!
    var model: CarDetailsContentModel!
    
    //车辆下单成功刷新车辆详情
    var carOrderSucceedBlock: BlockCarOrderSucceed!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("reserved_wheel", comment: "预留车盘")
        self.initTableView()
        self.initTabbarView()
    }
 

    func initTableView(){
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - TabbarHeight - 50), style: .plain)
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 2
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(CarInfoTableViewCell.self, forCellReuseIdentifier: "CarInfoTableViewCell")
        self.tableView.register(BookingPayTableViewCell.self, forCellReuseIdentifier: "BookingPayTableViewCell")
        self.tableView.backgroundColor = .white
        self.view.addSubview(self.tableView)
    }
    
    
    func initTabbarView() {
        
        self.protocolBtn = UIButton(frame: CGRect(x: 14, y: kScreenHeight - 40 - TabbarHeight, width: 30, height: 30))
        self.protocolBtn.setTitle(MMLocalizedString("read_and_agree", comment: "已阅读并同意"), for: .normal)
        self.protocolBtn.setImage(UIImage(named: "icon_check_normal"), for: .normal)
        self.protocolBtn.setImage(UIImage(named: "icon_check_select"), for: .selected)
        self.protocolBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 13)
        self.protocolBtn.setTitleColor(Theme.titleLabColor, for: .normal)
        self.protocolBtn.addTarget(self, action: #selector(protocolBtnAntion(sender:)), for: .touchUpInside)
        self.view.addSubview(self.protocolBtn)
        
        let agreementBtn = UIButton(frame: CGRect(x: self.protocolBtn.right, y: kScreenHeight - 60 - TabbarHeight, width: 150, height: 30))
        agreementBtn.setTitle(MMLocalizedString("car_order_agreement", comment: "《车辆订购协议》"), for: .normal)
        agreementBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 13)
        agreementBtn.setTitleColor(Theme.titleLabColor, for: .normal)
        agreementBtn.addTarget(self, action: #selector(agreementBtnAntion), for: .touchUpInside)
        agreementBtn.contentHorizontalAlignment = .left
        self.view.addSubview(agreementBtn)
        
        self.protocolBtn.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.height.equalTo(30)
            make.bottom.equalTo(-TabbarHeight)
        }
        
        agreementBtn.snp.makeConstraints { make in
            make.left.equalTo(self.protocolBtn.snp.right)
            make.height.equalTo(30)
            make.bottom.equalTo(-TabbarHeight)
        }
        
        
        let goPayBtn = UIButton(frame: CGRect(x: 14, y: protocolBtn.bottom + 14, width: kScreenWidth - 28, height: 46))
        goPayBtn.backgroundColor = Theme.mainColor
        goPayBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        goPayBtn.layer.cornerRadius = 8
        goPayBtn.clipsToBounds = true
        goPayBtn.setup_titleColor(color: .white)
        goPayBtn.setup_titleLabel(text: MMLocalizedString("immediate_payment", comment: "立即付款"))
        goPayBtn.addTarget(self, action: #selector(goPayBtnAntion), for: .touchUpInside)
        self.view.addSubview(goPayBtn)
        
    }
    
    
    ///订购协议
    func requestOrderAgreement() {
        self.view.showLoadingHUDText(nil)
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.orderAgreement(param: ["":""]), objectType: AboutUsResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! AboutUsResModel
            if resultObj.code == "1" {
                let vc = ProtocolViewController()
                vc.titleStr = MMLocalizedString("order_agreement", comment: "订购协议")
                vc.contentHtml = resultObj.data?.content ?? ""
                vc.modalPresentationStyle = .overFullScreen
                self.present(vc, animated: false)
                vc.backBlock = { [weak self] in
                    self?.protocolBtn.isSelected = true
                    self?.haveRead = true
                }
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    ///去支付操作
    func requestUsedcarOrder() {
        self.view.showLoadingHUDText(nil)
        
        let param: [String: String] = [
            "orderPrice": "\(self.model?.orderPrice ?? 0)",
            "usedcarId": "\(self.model?.id ?? 0)",
        ]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.usedcarOrder(param: param), objectType: ConfirmOrderModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! ConfirmOrderModel
            if resultObj.code == "1" {
                
                //刷新车辆详情
                if self.carOrderSucceedBlock != nil{
                    self.carOrderSucceedBlock()
                }
                
                let tempOrder = OrderContentListModel()
                tempOrder.orderNo = resultObj.data?.orderNo ?? ""
                tempOrder.price = self.model?.orderPrice ?? 0
                let vc = PaymentViewController()
                vc.orderContentModel = tempOrder
                vc.modalPresentationStyle = .overFullScreen
                self.present(vc, animated: false)
                
                vc.pushFirstDataBlock = {[weak self] urlStr in
                    let vc = MyWebController()
                    vc.urlStr = urlStr
                    vc.titleStr = MMLocalizedString("confirm_first_pay", comment: "FirstData支付")
                    self?.navigationController?.pushViewController(vc, animated: false)
                }
                
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    
    
    
    
    
    
    //MARK: - Antion
    //订购协议
    @objc func protocolBtnAntion(sender: UIButton) {
        if self.protocolBtn.isSelected == false {
            self.requestOrderAgreement()
        }else{
            sender.isSelected = !sender.isSelected
        }
    }
    
    @objc func agreementBtnAntion() {
        self.requestOrderAgreement()
    }
    
    
    //去支付
    @objc func goPayBtnAntion() {
        
        if self.protocolBtn.isSelected == false{
            self.popOverView()
            return
        }
        
            
        self.requestUsedcarOrder()
    }
    
    
    func popOverView(){
        
        //获取labede的坐标在整个view上的位置
        var point = self.protocolBtn.center
        point = CGPoint.init(x: point.x - 30, y: point.y - 15)
        
        let tipLab = UILabel(frame: CGRect(x: 14, y: 10, width: kScreenWidth*2/3 - 24, height: 100))
        tipLab.text = MMLocalizedString("subscription_agreement", comment: "请阅读并同意车辆订购协议")
        tipLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 13)
        tipLab.textColor = Theme.whiteColor
        tipLab.numberOfLines = 0
        tipLab.lineBreakMode = .byTruncatingTail
        tipLab.sizeToFit()
        
        var tempW = tipLab.frame.size.width + 28
        if tempW > kScreenWidth * 2/3 {
            tempW = kScreenWidth * 2/3
        }
        
        if tempW < 120 {
            tempW = 120
        }
        if self.overView != nil {
            self.overView = nil
        }
        overView = WBPopOverView.init(origin: point, width: tempW, height: Float(tipLab.frame.size.height) + 20, direction: WBArrowDirection.down1)
        overView?.backgroundColor = UIColor.init(hex: 0xffffff, alpha: 0.1)
        overView?.backView.backgroundColor = Theme.titleLabColor
        overView?.backView.layer.masksToBounds = true
        overView?.backView.layer.cornerRadius = 4
        overView?.backView.addSubview(tipLab)
        overView?.pop()
    }
    
    
}

extension ReservedWheelViewController: UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "CarInfoTableViewCell", for: indexPath) as! CarInfoTableViewCell
            if self.model != nil{
                cell.setModel(model: self.model)
            }
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "BookingPayTableViewCell", for: indexPath) as! BookingPayTableViewCell
            if self.model != nil{
                cell.setModel(model: self.model)
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let bgView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        bgView.backgroundColor = .white
        return bgView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let bgView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        bgView.backgroundColor = .clear
        return bgView
    }
   
}
